package com.itheima.reggie.util;


import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * excel工具类
 */
public class ExcelUtils {





    /**
     * 下载表格
     * @param workbook
     * @param fileName
     * @param response
     * @return
     * @throws IOException
     */
    public static boolean downloadExcel(Workbook workbook, String fileName, HttpServletResponse response) throws IOException {
        try {
            //将excel文件以流形式输出
            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;

            //将Excel的数据写入字节数组输出流
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
            //将Excel的数据转换为字节数组
            byte[] bytes = byteArrayOutputStream.toByteArray();
            //创建字节数组输入流
            InputStream inputStream = new ByteArrayInputStream(bytes);

            //设置浏览器强制下载（不弹窗）
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx","utf-8"));

            //获取response输出流
            ServletOutputStream outputStream = response.getOutputStream();

            bis = new BufferedInputStream(inputStream);//包含excel数据，负责读取
            bos = new BufferedOutputStream(outputStream);//输出

            int read = 0 ;
            byte[] buff = new byte[2048];
            while (-1 != (read = bis.read(buff,0,buff.length))){
                bos.write(buff,0,read);
            }

            bis.close();
            bos.close();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return true;
        }

    /**
     * 表格插入图片
     * @param imagePath 图片路径
     * @param workbook 表格对象
     * @param sheet 工作单对象
     * @param row 坐标——行
     * @param coll  坐标——列
     * @throws IOException
     */
    public static void insertImage(String imagePath, Workbook workbook, Sheet sheet, int row, int coll) throws IOException {
        InputStream is = new FileInputStream(imagePath);
        byte[] bytes = IOUtils.toByteArray(is);
        int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
        CreationHelper creationHelper = workbook.getCreationHelper();
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        ClientAnchor clientAnchor = creationHelper.createClientAnchor();
        clientAnchor.setRow1(row);
        clientAnchor.setCol1(coll);
        Picture picture = drawing.createPicture(clientAnchor, pictureIdx);
        picture.resize(1, 1);
    }

}
